package com.example.startapp.json;

import android.content.Context;
import android.util.Log;

import com.example.startapp.entity.HomeData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonPaper {
    private static JsonPaper jsonPaper;
    public JsonPaper(){

    }
    public static JsonPaper getInstance(){
        if (jsonPaper==null){
            jsonPaper=new JsonPaper();
        }
        return jsonPaper;
    }

    private String read(InputStream in){
        BufferedReader reader=null;
        StringBuilder sb=null;
        String line=null;
        try {
            sb=new StringBuilder();
            reader=new BufferedReader(new InputStreamReader(in));//字节流转化字符流
            while((line=reader.readLine())!=null){
                sb.append(line);
                sb.append("\n");
            }
        }catch (IOException e){
            e.printStackTrace();
            return "";
        }finally {
            try{
                if (in!=null) in.close();
                if (reader!=null) reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return sb.toString();

    }
    public List<HomeData> getInfosFromJson(Context context){
        List<HomeData> homeDataInfos=new ArrayList<>();
        InputStream is=null;
        try {
            is=context.getResources().getAssets().open("text.json");
            String json=read(is);//获得json数据
            Gson gson=new Gson();
            Log.e("11","success");
            Type listType=new TypeToken<List<HomeData>>(){

            }.getType();
            List<HomeData> infoList=gson.fromJson(json,listType);
            return infoList;
        }catch (IOException e){
            e.printStackTrace();
            Log.e("11","fail");
        }
        return homeDataInfos;
    }







}
